package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.listener.WebListener;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据dubbo获取User对象，根据多对多对象获取菜单和权限
        User user = userService.findByUsername(username);

        if(user == null) {
            return null;
        }

        Integer loginNumber = WebListener.Number;

        if(loginNumber >= 3) {
            return null;
        }

        //获取角色
        Set<Role> roles = user.getRoles();

        //创建GrantedAuthority对象，接受角色和权限
        List<GrantedAuthority> list = new ArrayList<>();

        if(roles != null) {
            for (Role role : roles) {
                //将角色放入到GrantedAuthority中
                list.add(new SimpleGrantedAuthority(role.getKeyword()));

                //获取权限
                Set<Permission> permissions = role.getPermissions();

                if(permissions != null) {
                    for (Permission permission : permissions) {
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }

            }
        }

        //将user的用户和密码，权限
        UserDetails SecurityUser = new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);

        return SecurityUser;
    }
}
